package com.android.manghe.search.presenter

import android.os.Handler
import android.os.Message
import android.text.TextUtils
import com.android.base.frame.presenter.XPresenter
import com.android.base.okhttp.okUtil.OKHttpUtil
import com.android.base.tools.EmptyUtil
import com.android.manghe.common.model.BaseBack
import com.android.manghe.config.ConstantsUrl
import com.android.manghe.common.model.AuctionSocketRes
import com.android.manghe.common.model.JoinAuctionSocketRes
import com.android.manghe.search.activity.SearchCategoryActivity
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_search.*
import okhttp3.Call
import java.util.ArrayList
import java.util.HashMap

class PCategorySearch : XPresenter<SearchCategoryActivity>(){

    private var mCurrentPage = 1
    private val PageSize = "10"
    private val mAuctionList = ArrayList<AuctionSocketRes.ListBean>()

    private var text = ""

    fun search(isRefresh :Boolean, text: String){

        if(text.isNotEmpty()){
            this.text = text
        }

        if (isRefresh) {
            mCurrentPage = 1
            mAuctionList.clear()
        }
        val data = HashMap<String, String>()
        data["page"] = mCurrentPage.toString() + ""
        data["size"] = PageSize
        data["q"] = this.text
        val headMap = HashMap<String, String>()
//        headMap["UID"] = UserHolder.getUID(v)
//        headMap["TOKEN"] = UserHolder.getUserInfo(v)!!.TOKEN
        OKHttpUtil(v).urlByHeadData(
            ConstantsUrl.domain + ConstantsUrl.AUCTION_SEARCH,
            data,
            headMap
        )
            .get()
            .execute(object : BaseBack<AuctionSocketRes>() {

                override fun onSuccess(call: Call, res: AuctionSocketRes?) {
                    if (res != null) {
                        if(res.code == 0){
                            if(res.list.isNullOrEmpty()){
                                v.noData()
                            }else{
                                mAuctionList.addAll(res.list)
                                v.searchOk(mAuctionList)
                                v.refreshLayout.isEnableLoadMore = mAuctionList.size != res.list_total
                                mCurrentPage++
                            }
                        }else{
                            v.searchFail(res.msg)
                        }
                    }else{
                        v.searchFail(null)
                    }
                }

                override fun onFailure(e: Exception) {
                    super.onFailure(e)
                    v.searchFail(null)
                }

                override fun onComplete() {
                    v.hideLoadingDialog()
                }
            })
    }

    fun dealSocketData(json: String) {
        if (!EmptyUtil.check(json)) {
            if (json.contains("join_auction")) {
                try {
                    val socketRes = Gson().fromJson(json, JoinAuctionSocketRes::class.java)
                    if (!EmptyUtil.check(socketRes)) {
                        updateShowingData(socketRes)
                    }
                } catch (e: Exception) {
                }
            }
        }
    }

    val handler = object :Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            try{
                v.modifyItemData(mAuctionList[modifyPosition],modifyPosition)
            }catch (e:java.lang.Exception){
                e.printStackTrace()
            }
        }
    }
    private var modifyPosition = -1
    private fun updateShowingData(res : JoinAuctionSocketRes){
        if(mAuctionList.isNullOrEmpty())
            return

        Thread(object : Runnable{
            override fun run() {
                try{
                    for((i , action) in mAuctionList.withIndex()){
                        if(TextUtils.equals(action.id, res.id.toString())){
                            mAuctionList[i].time = res.time
                            modifyPosition = i
                            handler.sendEmptyMessage(0)
                            break
                        }
                    }
                }catch (e: java.lang.Exception){
                    print(e.localizedMessage)
                }
            }
        }).start()
    }
}